﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Furion;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using ADSTS_SERVER.Models;
using ADSTS_SERVER.ViewModels.Robot;
using ADSTS_SERVER.VO.Robot;
using Mapster;
using Masuit.Tools.Files;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace ADSTS_SERVER.Controllers
{
    /// <summary>
    /// 机器人
    /// </summary>
    [DynamicApiController]
    public class LnsRobotController
    {
        private readonly ILogger<LnsRobotController> logger;
        private readonly ISevenZipCompressor sevenZipCompressor;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public LnsRobotController(ISqlSugarClient sqlSugarClient, ISevenZipCompressor sevenZipCompressor)
        {
            this.db = sqlSugarClient;
            this.sevenZipCompressor = sevenZipCompressor;
        }

        /// <summary>
        /// 机器人列表
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromBody] RobotSearchForm dtsf)
        {
            RefAsync<int> total = 0;
            List<Robot> robots = await db.Queryable<Robot>()
                .Mapper(dt => dt.User, dt => dt.UId, dt => dt.User.Id)
                .Where(dt => dt.IsActive == 1)
                .WhereIF(!string.IsNullOrEmpty(dtsf.Content), dt => dt.Name.Contains(dtsf.Content) || dt.Description.Contains(dtsf.Content))
                .WhereIF(!string.IsNullOrEmpty(dtsf.Tag), dt => dt.Tag == dtsf.Tag)
                .WhereIF(dtsf.UId != 0, dt => dt.UId == dtsf.UId)
                .ToPageListAsync(dtsf.PageIndex, dtsf.PageSize, total);

            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = robots,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 机器人分类列表
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> TagList()
        {
            List<string> tags = await db.Queryable<Robot>().Distinct().Select(rbt => rbt.Tag).ToListAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = tags,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 增加机器人
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] RobotSaveVO vo)
        {
            //TypeAdapterConfig<List<Sensor>, List<Sensor>>.NewConfig().MapWith(json => json);
            await db.Insertable<Robot>(vo.Adapt<Robot>()).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除机器人
        /// </summary>
        /// <param name="dtddf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Delete([FromBody] RobotDeleteForm dtddf) {
            await db.Updateable<Robot>(new Robot { IsActive = 0 }).UpdateColumns(mx => mx.IsActive).Where(mx => mx.Id == dtddf.Id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改机器人
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] RobotUpdateVO vo) {
            //TypeAdapterConfig<List<Sensor>, List<Sensor>>.NewConfig().MapWith(json => json);
            await db.Updateable<Robot>(vo).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = vo,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 查看机器人
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Show([FromBody] RobotShowForm dtsf) {
            Robot robot = await db.Queryable<Robot>()
                .InSingleAsync(dtsf.Id);
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = robot,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 解析模型
        /// </summary>
        /// <param name="dtsf"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Unzip([FromBody] RobotUnzipVO vo)
        {
            if (Path.HasExtension(vo.RobotUrl)) {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "非模型",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            string filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, vo.RobotUrl.Substring(1));

            // 解压文件
            string dir = $"mshow{vo.UId}";
            string unzipPath = Path.Combine(App.WebHostEnvironment.WebRootPath, dir);
            if (Directory.Exists(unzipPath)) {
                Directory.Delete(unzipPath, true);
            }
            Directory.CreateDirectory(unzipPath);
            sevenZipCompressor.Decompress(filePath, unzipPath);

            DirectoryInfo theFolder = new(Path.Combine(unzipPath, "gltf"));
            FileInfo[] file = theFolder.GetFiles();//获取所在目录的文件
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = $"{dir}/gltf/{file[0].Name}",
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
